package com.gitee.feizns.explore.data_structure.visual.frame.bubble;

import com.gitee.feizns.explore.data_structure.visual.frame.Utils;

import javax.swing.*;
import java.awt.*;
import java.util.function.Consumer;

/**
 * @author feizns
 * @since 2020/1/2
 */
public class View extends JFrame {

    private int w = 800;

    private int h = 800;

    private int f;

    private Consumer<Graphics2D> consumer;

    private boolean running = true;

    public View(String title, int f, Consumer<Graphics2D> consumer) {
        super(title);
        this.f = f;
        this.consumer = consumer;
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(w, h);
        setResizable(false);
        setContentPane(new ContentPanel());
        setLocation(200, 200);
    }

    public int getW() { return w; }

    public int getH() { return h; }

    public View(Consumer<Graphics2D> consumer) {
        this("Welcome.!!!", 50, consumer);
    }

    public void start() {
        new Thread(() -> {
            while (true) {
                Utils.sleep(f);
                if ( running )
                    repaint();
            }
        }).start();
    }

    public void status(boolean status) {
        this.running = status;
    }

    public void switchStatus() {
        this.running = !this.running;
    }

    class ContentPanel extends JPanel {

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            consumer.accept((Graphics2D) g);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(w, h);
        }
    }

}
